package com.clkj.xiuzheng.service.shangcheng;

import com.clkj.xiuzheng.dao.shangcheng.*;
import com.clkj.xiuzheng.dao.shangcheng.TopicCategoryMapper;
import com.clkj.xiuzheng.dao.shangcheng.TopicCommentMapprt;
import com.clkj.xiuzheng.dao.shangcheng.TopicOrVideoMapper;
import com.clkj.xiuzheng.pojo.common.DateFormatHelper;
import com.clkj.xiuzheng.pojo.common.ExcelRead;
import com.clkj.xiuzheng.pojo.common.OSSUtil;
import com.clkj.xiuzheng.pojo.shangcheng.*;
import com.clkj.xiuzheng.pojo.common.UploadFile;
import com.clkj.xiuzheng.pojo.shangcheng.TopicCategory;
import com.clkj.xiuzheng.pojo.shangcheng.TopicComment;
import com.clkj.xiuzheng.pojo.shangcheng.TopicOrVideo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ScBaiKeServiceImpl implements ScBaiKeService{

    @Autowired
    private TopicOrVideoMapper scBaiKeMapper;
    @Autowired
    private TopicCategoryMapper topicCategoryMapper;
    @Autowired
    private TopicCommentMapper commentMapper;
    @Autowired
    private CollectOrPriseMapper collectorMapper;
    @Autowired
    private ScProductMapper productMapper;

    private Map map;
    @Autowired
    private TopicCommentMapprt topicCommentMapprt;

    @Override
    public PageInfo getTopicOrVideoList(Integer companyId, Integer pageSize, Integer pageNum,Integer flag) {
        PageHelper.startPage(pageNum, pageSize);
        List<TopicOrVideo> list = scBaiKeMapper.getTopicOrVideoList(companyId,flag);
        return new PageInfo(list);
    }

    @Override
    public void addTopicOrVideo(TopicOrVideo video, HttpServletRequest request) {
        video.setCreatedTime(DateFormatHelper.currentTimes());
        video.setBaikeStatus(video.getBaikeStatus());
        MultipartFile headImage = ((MultipartRequest) request).getFile("mainImg");
        if(headImage!=null){
            String mainImg = OSSUtil.uploadingImg(headImage, "xiuzheng/topic");
            video.setBaikeImg(mainImg);
        }
        MultipartFile content = ((MultipartRequest) request).getFile("content");
        if(content!=null){
            String contentImg = OSSUtil.uploadingImg(content, "xiuzheng/topic");
            video.setBaikeContent(contentImg);
        }
        scBaiKeMapper.insertSelective(video);

    }

    @Override
    public void updateStatus(String ids, Integer status, Integer flag) {
        String []id = ids.split(",");
        Example example = new Example(TopicOrVideo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("baikeId", Arrays.asList(id));
        TopicOrVideo video = new TopicOrVideo();
        if(flag==0){
            video.setBaikeStatus(status);

        }else{
            video.setIsTop(flag);
        }
        scBaiKeMapper.updateByExampleSelective(video,example);

    }

    @Override
    public void addOrUpdateCategory(TopicCategory category) {
        if(category.getCategoryId()==null){
            topicCategoryMapper.insertSelective(category);
        }
        else{
            topicCategoryMapper.updateByPrimaryKeySelective(category);
        }
        category = null;

    }

    @Override
    public List<TopicCategory> listCategory(Integer companyId) {
        Example example = new Example(TopicCategory.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("companyId",companyId);
        return topicCategoryMapper.selectByExample(example);
    }

    @Override
    public void updateCategoryStatus(String ids, Integer status) {
        String []id = ids.split(",");
        Example example = new Example(TopicCategory.class);
        Example.Criteria criteria =  example.createCriteria();
        criteria.andIn("categoryId",Arrays.asList(id));
        TopicCategory category = new TopicCategory();
        category.setCategoryStatus(status);
        topicCategoryMapper.updateByExampleSelective(category,example);
        ids = null;
        id = null;
        example = null;
        criteria = null;
        category = null;

    }

    @Override
    public void importComment(HttpServletRequest request) {
        try {
            MultipartFile file = ((MultipartRequest) request).getFile("file");
            File excelFile = null;
            excelFile = UploadFile.multipartFileToFile(file);
            List<Map<String, Object>> result = ExcelRead.ReadExcelByRC(excelFile, file.getContentType(), 2, -1, false);
            TopicComment TopicComment = null;
            List<TopicComment> topicComments =new ArrayList<>();
            for (int i = 0; i < result.size(); i++) {
                if(result.get(i).get("1")==null||result.get(i).get("1").equals("null")){
                    break;
                }
                TopicComment = new TopicComment();
                TopicComment.setCommentDetail(result.get(i).get("1").toString());
                TopicComment.setUserId(Integer.parseInt(result.get(i).get("2").toString()));
                TopicComment.setCommentTime(result.get(i).get("3").toString());
                TopicComment.setParentId(Integer.parseInt(result.get(i).get("4").toString()));
                TopicComment.setTopicId(Integer.parseInt(result.get(i).get("5").toString()));
                topicComments.add(TopicComment);
            }
            if(topicComments.size()>0){
              topicCommentMapprt.insertList(topicComments);
            }
            file= null;
            excelFile= null;
            result = null;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Map listBaiKe(Integer categoryId, Integer page, Integer size) {
        map = new HashMap<>();
        List<TopicCategory> categories = null;
        if(categoryId==0){
            Example example = new Example(TopicCategory.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("categoryStatus",1);
            categories = topicCategoryMapper.selectByExample(example);
        }
        PageHelper.startPage(page, size);
        Example examples = new Example(TopicOrVideo.class);
        Example.Criteria criterias = examples.createCriteria();
        criterias.andEqualTo("baikeStatus",1);
        if(categoryId==0){
            categoryId=  categories.get(0).getCategoryId();
        }
        criterias.andEqualTo("categoryId",categoryId);
        examples.orderBy("isTop").asc();
        map.put("categories", categories);
        map.put("topicOrVideo",new PageInfo<>(scBaiKeMapper.selectByExample(examples)));
        return map;
    }

    @Override
    public Map listBaiKeComment(Integer baiKeId, Integer userId,Integer productId) {
        List<TopicComment> comments =commentMapper.listComment(baiKeId);
        List<CollectOrPrise> collect =collectorMapper.listCollect(userId,baiKeId);
        SProduct product = null;
        if(productId!=0){
            product = productMapper.selectByPrimaryKey(productId);
        }
        map = new HashMap<>();
        map.put("comments", comments);
        map.put("collect", collect);
        map.put("product", product);
        return map;
    }

    @Override
    public PageInfo listBaiKeSearch(String searchName, Integer page, Integer size) {
        PageHelper.startPage(page, size);
        Example example = new Example(TopicOrVideo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andCondition("( baike_title like '%"+searchName+"%' or baike_content like '%"+searchName+"%' or baike_subtitle like '%"+searchName+"%' )");
        criteria.andEqualTo("baikeStatus",1);
        example.orderBy("isTop").desc();
        return new PageInfo(scBaiKeMapper.selectByExample(example));
    }

    @Override
    public void addCollectOrPrise(Integer productId, Integer userId, Integer type, Integer flag, Integer status) {
            /**
             * @ApiParam(name = "productId", value = "商品或文章视频")@RequestParam Integer productId,
             *                                   @ApiParam(name = "userId", value = "用户ID")@RequestParam Integer userId,
             *                                   @ApiParam(name = "type", value = "0为点赞，1为收藏")@RequestParam Integer type,
             *                                     @ApiParam(name = "flag", value = "0为商品，1为文章2为视频视频")@RequestParam Integer flag,
             *                                     @ApiParam(name = "status", value = "1为点赞或收藏，0为取消")@RequestParam Integer status
             *                                     */
            if(status==1){
                CollectOrPrise collect = new CollectOrPrise();
                collect.setCollectFlag(type);
                collect.setCollectTime(DateFormatHelper.currentTimes());
                collect.setCollectType(flag);
                collect.setProductId(productId);
                collect.setUserId(userId);
                collectorMapper.insertSelective(collect);
            }else{
                Example example = new Example(CollectOrPrise.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("userId",userId).andEqualTo("productId",productId).andEqualTo("collectFlag",type);
                collectorMapper.deleteByExample(example);
            }
            if(flag==1||flag==2){
                if(type==0){
                    scBaiKeMapper.updatePrise(productId,status==0?-1:1);
                }else{
                    scBaiKeMapper.updateCollect(productId,status==0?-1:1);
                }

            }



    }

    @Override
    public void addTopicComment(Integer topicId, Integer userId, String commentDetail, Integer parentId) {
        TopicComment comment = new TopicComment();
        comment.setCommentDetail(commentDetail);
        comment.setUserId(userId);
        comment.setCommentTime(DateFormatHelper.currentTimes());
        comment.setParentId(parentId);
        comment.setTopicId(topicId);
        commentMapper.insertSelective(comment);
        scBaiKeMapper.updateCommentNum(topicId);

    }

    @Override
    public PageInfo listComment(Integer page, Integer size, Integer topicId) {
        PageHelper.startPage(page, size);
        return new PageInfo(commentMapper.listAllComment(topicId));
    }

    @Override
    public List<TopicOrVideo> listAllTopicOrVideo() {
        return scBaiKeMapper.selectAll();
    }

    @Override
    public void deleteComment(String ids) {
        Example example = new Example(TopicComment.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("commentId",Arrays.asList(ids.split(",")));
        commentMapper.deleteByExample(example);

    }

    @Override
    public List<CollectOrPrise> listCollect(Integer userId) {
        return collectorMapper.listCollectByUser(userId);
    }

    @Override
    public void setCommentTop(String ids, Integer type) {
        String[] split = ids.split(",");
        Example example = new Example(TopicComment.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("commentId",Arrays.asList(split));
        TopicComment topicComment = new TopicComment();
        topicComment.setIsTop(type);
        commentMapper.updateByExampleSelective(topicComment,example);
    }

}
